import type { NextApiResponse } from 'next';
import * as newsService from '@/common/service/g_news';
import R from '@common/type/response';
import { AuthenticatedRequest, withAuth } from '@common/middleware/auth';

export async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
  const { id } = req.query;
  if (!id) {
    R.error(res, '缺少ID');
    return;
  }
  if (req.method === 'GET') {
    const data = await newsService.getNewsById(Number(id));
    R.success(res, data);
  } else if (req.method === 'PUT' || req.method === 'PATCH') {
    try {
      const affected = await newsService.updateNews(Number(id), req.body);
      R.success(res, affected);
    } catch (error: any) {
      console.error('更新新闻错误:', error);
      R.error(res, error.message || '更新新闻失败');
    }
  } else if (req.method === 'DELETE') {
    const affected = await newsService.deleteNews(Number(id));
    R.success(res, affected);
  } else {
    R.error(res, 'Method Not Allowed');
  }
}

export default withAuth(handler); 